package com.nf.health.app.activity.home.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.VolleyError;
import com.nf.health.app.R;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.activity.home.DoctorDetailsActivity;
import com.nf.health.app.fragment.NoIBaseFragment;
import com.nf.health.app.http.Act;
import com.nf.health.app.http.VolleyErrorHelper;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DialogHelp;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;

import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.DateUtils;

/**
 * 预约挂号
 * Created by changpeng on 2017/4/10 0010.
 */

public class BookingRegisteredFragment extends NoIBaseFragment implements DoctorDetailsActivity.OpFragment{


    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.tv_name)
    TextView mTvName;
    @Bind(R.id.tv_sex)
    TextView mTvSex;
    @Bind(R.id.et_idcard)
    EditText mEtIdcard;
    @Bind(R.id.et_phone)
    EditText mEtPhone;
    @Bind(R.id.btn_commit)
    Button mBtnCommit;

    private String mName,mSex,mIdcard,mPhone;
    private String mDoctorId = "";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        addViewFillInRoot(R.layout.fragment_booking_registered);
        ButterKnife.bind(this, rootView);
        initListener();
        initData();
        initView();
    }

    private void initData() {
        UserInfo userInfo = PreferenceHelper.getUser();
        mName = userInfo.getNick();
        mSex = userInfo.getSex();
        mIdcard = userInfo.getIdcard();
        mPhone = PreferenceHelper.getString(PreferenceHelper.USERNAME,"");
    }

    private void initListener() {
        mTvTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePicker mPicker = new DatePicker(getActivity());
                mPicker.setRange(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.YEAR)+1);
                mPicker.setOffset(1);
                mPicker.setSubmitTextColor(getResources().getColor(R.color.theme_color));
                final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
                final int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
                final int currentDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
                final int currentMaxDays = DateUtils.calculateDaysInMonth(currentYear, currentMonth);
                mPicker.setSelectedItem(currentYear, currentMonth, currentDay);
                mPicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                    @Override
                    public void onDatePicked(String year, String month, String day) {
                        int sMonth = Integer.parseInt(month);
                        int sDay = Integer.parseInt(day);
                        int sMaxDays = DateUtils.calculateDaysInMonth(stringToYearMonthDay(year), stringToYearMonthDay(month));
                        //选择月份为当前月
                        if(currentMonth == sMonth){
                            if(sDay - currentDay >= 0) {
                                if (sDay - currentDay <= 7) {
                                    mTvTime.setText(year + "-" + month + "-" + day);
                                } else {
                                    showToast("只能选择从当日起一周内的时间作为挂号时间");
                                }
                            }else{
                                showToast("只能选择从当日起一周内的时间作为挂号时间");
                            }
                        }

                        if(currentMonth + 1 == sMonth){
                            if(sDay + (currentMaxDays - currentDay) < 7){
                                mTvTime.setText(year + "-" + month + "-" + day);
                            }else{
                                showToast("只能选择从当日起一周内的时间作为挂号时间");
                            }
                        }

                        if(sMonth - currentMonth < 0){
                            showToast("只能选择从当日起一周内的时间作为挂号时间");
                        }
                        //选择月份比当前月份大2个月以上
                        if(sMonth - currentMonth >= 2){
                            showToast("只能选择从当日起一周内的时间作为挂号时间");
                        }

                    }
                });
                mPicker.show();
            }
        });
        mBtnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitData();
            }
        });
    }

    private void initView() {
        mTvName.setText(mName);
        mTvSex.setText(Util.getSex(mSex));
        mEtIdcard.setText(mIdcard);
        mEtPhone.setText(mPhone);
    }


    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if(Act.Flag.FLAG_YL_REGISTRATION.equals(actionName)){
            provider.ylRegistrationState(mDoctorId);
            DialogHelp.getMessageDialog(getActivity(), "预约成功", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
        }else if(Act.Flag.FLAG_YL_REGISTRATION_STATE.equals(actionName)){
            JSONObject object1= JSONObject.parseObject(object+"");
            String flag = object1.getString("flag");
            changeButtonState(flag);

        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        if (TextUtils.isEmpty(response)) {
            //处理error
            showToast(VolleyErrorHelper.getMessage(error));
        } else {
            //处理response
            String code = JsonUtils.getKey2Value(response, "code");
            if("2002".equals(code)){
                PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
                showToast("登录失效，请重新登录");
                //未登录
                ActivityUtils.skipActivity(getActivity(), LoginActivity.class);
//                EmUtil.logout();//退出环信
            }else{
                if(TextUtils.isEmpty(JsonUtils.getFiledData(response,"msg"))){

                }else{
                    String err = JsonUtils.getFiledData(response, "msg");
                    //showToast(JsonUtils.getFiledData(response, "msg"));
                    DialogHelp.getMessageDialog(getActivity(), err, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).show();
                }
            }
        }
    }

    private void commitData(){
        String time = mTvTime.getText().toString().trim();
        String name = mTvName.getText().toString().trim();
        String sex = mTvSex.getText().toString().trim();
        String idcard = mEtIdcard.getText().toString().trim();
        String phone = mEtPhone.getText().toString().trim();
        if("请选择".equals(time)){
            showToast("请选择预约时间");
            return;
        }
        if(TextUtils.isEmpty(idcard)){
            showToast("请填写身份证");
            return;
        }

        if(TextUtils.isEmpty(phone)){
            showToast("请填写手机号");
            return;
        }

      //  provider.ylRegistration(mDoctorId,idcard,name,phone,time,mSex);

    }



    private int stringToYearMonthDay(String text) {
        if (text.startsWith("0")) {
            //截取掉前缀0以便转换为整数
            text = text.substring(1);
        }
        return Integer.parseInt(text);
    }

    @Override
    public void onAction(String goodAt, String content, String doctorId) {
        mDoctorId = doctorId;
        provider.ylRegistrationState(mDoctorId);
    }

    private void changeButtonState(String flag){
        if(flag.equals("0")){//可预约
            mBtnCommit.setEnabled(true);
            mBtnCommit.setText("提交预约");
            mBtnCommit.setBackgroundColor(getResources().getColor(R.color.theme_color));
        }else if(flag.equals("2")){//不可预约
            mBtnCommit.setEnabled(false);
            mBtnCommit.setText("已预约");
            mBtnCommit.setBackgroundColor(getResources().getColor(R.color.btn_enable_false_color));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
